package com.glx.test.controller;

import com.glx.test.response.FileResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/question")
public class QuestionController {
//    NginxFiles: http://localhost:7071/files/
//    LocalFiles: /Users/gulixiang/Desktop/Design-Code/files/

    @Value("${NginxFiles}")
    private String nginxFilesPath;

    @Value("${LocalFiles}")
    private String localFilesPath;

    @PostMapping("/uploadFiles")
    public FileResponse uploadFile(@RequestParam("file") MultipartFile file) {
// 定义存储的子目录
        String subDirectory = "question_picture/";
        String fileName = UUID.randomUUID() + "_" + file.getOriginalFilename();
        File destDir = new File(localFilesPath + subDirectory);
        File destFile = new File(destDir, fileName);

        try {
            // 创建子目录（如果不存在）
            if (!destDir.exists()) {
                destDir.mkdirs();
            }

            // 保存文件
            file.transferTo(destFile);

            // 文件外部访问路径
            String fileUrl = nginxFilesPath + subDirectory + fileName;
            return new FileResponse("success", "上传成功", fileUrl);
        } catch (IOException e) {
            // 异常处理
            return new FileResponse("fail", "上传失败：" + e.getMessage(), null);
        }
    }


    @DeleteMapping("/delete")
    public FileResponse deleteFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            // 验证 URL 是否以 nginxFilesPath 开头
            if (!fileUrl.startsWith(nginxFilesPath)) {
                System.out.println("URL 非法，无法解析");
                return new FileResponse("fail", "URL 非法，无法解析", null);
            }

            // 从 URL 中解析相对路径
            String relativePath = fileUrl.substring(nginxFilesPath.length());
            File fileToDelete = new File(localFilesPath + relativePath);

            System.out.println("相对路径：" + relativePath);
            // 检查文件是否存在
            if (!fileToDelete.exists()) {
                System.out.println("文件不存在");
                return new FileResponse("fail", "文件不存在", null);
            }

            // 删除文件
            if (fileToDelete.delete()) {
                System.out.println("文件删除成功");
                return new FileResponse("success", "文件删除成功", null);
            } else {
                return new FileResponse("fail", "文件删除失败", null);
            }
        } catch (Exception e) {
            return new FileResponse("fail", "删除文件时发生错误：" + e.getMessage(), null);
        }
    }
}
